import ToolSelect from '@/core/tools/select';
import ToolSelection from '@/core/tools/selection';
import { createSlice, PayloadAction } from '@reduxjs/toolkit';
import { SerializableObject, Tool, ToolName } from '@/core/public';
import ToolBase from '@/core/tools/base';
import ToolPencil from '@/core/tools/pencil';

export type SerializableToolObject = SerializableObject & {
  name: ToolName
  label: string
}

export type ToolMap = {
  [K in ToolName]: Tool
}

export const toolMap: ToolMap = {
  select: new ToolSelect(),
  selection: new ToolSelection(),
  pencil: new ToolPencil(),
}

export type ToolClassMap = {
  [key in ToolName]: typeof ToolBase
}

export const toolClassMap: ToolClassMap = {
  select: ToolSelect,
  selection: ToolSelection,
  pencil: ToolPencil,
}

interface InitialState {
  list: SerializableToolObject[]
  active?: SerializableToolObject,
}


const initialState: InitialState = {
  list: Object.values(toolMap).map((tool: Tool) => {
    return tool.serialize()
  }),
  active: undefined,
}

export default createSlice({
  name: 'tools',
  initialState,
  reducers: {
    update: (state, action: PayloadAction<SerializableToolObject>) => {
      const index = state.list.findIndex((item) => item.name === action.payload.name);
      if(index > -1) {
        var newItem = {
          ...state.list[index],
          ...action.payload
        }
        state.list.splice(index, 1, newItem)
        if(state.active?.name == action.payload.name) state.active = newItem
      }
    },
    activate: (state, action: PayloadAction<ToolName>) => {
      state.active = state.list.find(item => item.name === action.payload)
    },
  },
});